import UserUpdateModal from '@/pages/userControl/components/UserUpdateModal';
import { uploadUsingPost } from '@/services/openAPI-backend/upLoadController';
import {
  changeAkandSkUsingPost,
  getCollectionsUsingGet,
  getLikesUsingGet,
  getLoginUserUsingGet,
  updateUserUsingPost,
} from '@/services/openAPI-backend/userController';
import {EyeOutlined,  PlusOutlined} from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { FormattedMessage} from '@umijs/max';
import {Drawer, GetProp, TabsProps, UploadProps} from 'antd';
import {
  Avatar,
  Button,
  Card,
  Col,
  Descriptions,
  List,
  Popconfirm,
  Row,
  Space,
  Tabs,
  Upload,
  message,
  notification,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import {
  collectInterfaceInfoUsingPost,
  likeInterfaceInfoUsingPost,
} from "@/services/openAPI-backend/interfaceInfoController";
import {keyframes} from "antd-style";
import { Link, history } from '@umijs/max';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const fadeIn = keyframes`
    0% {
        transform: translateY(50%);
    }
    100% {
        transform: translateY(0);
    }
`;
const DescriptionItem = ({ title, content }: DescriptionItemProps) => (
    <div
        className="site-description-item-profile-wrapper"
        style={{
          display: 'flex',
          marginBottom: 12,
          marginTop: 5,
          fontSize: 15,
        }}
    >
      {title}:
      <p
          style={{
            color: '#ad2102',
            marginLeft: 8,
            fontSize: 15,
          }}
      >
        {' '}
        {content}
      </p>
    </div>
);
const simpleColumns: ProColumns<API.UserUpdateRequest>[] = [
  {
    title: 'id',
    dataIndex: 'id',
    valueType: 'index',
  },
  {
    title: '昵称',
    dataIndex: 'userName',
    valueType: 'text',
  },

  {
    title: '用户名',
    dataIndex: 'userAccount',
    valueType: 'text',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '您不能做无名氏啊',
        },
      ],
    },
  },
  {
    title: '性别',
    dataIndex: 'gender',
    valueEnum: {
      男: {
        text: <FormattedMessage id="male" defaultMessage="男" />,
      },
      女: {
        text: <FormattedMessage id="female" defaultMessage="女" />,
      },
    },
  },
  {
    title: '自我介绍',
    dataIndex: 'selfIntroduction',
    valueType: 'textarea',
  },
];

//页内表格

const UserCenter: React.FC = () => {
  const [like, setLike] = useState<API.InterfaceInfo[]>();
  const [loading, setLoading] = useState(false);
  let imminentUser = JSON.parse(sessionStorage.getItem('loginUser'));
  const [currentUser, setCurrentUser] = useState<API.User>({ imminentUser });
  const [imageUrl, setImageUrl] = useState<string>();
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [data, setData] = useState<API.InterfaceInfo[]>();
  const [showSecretKey, setShowSecretKey] = useState<boolean>(false);
  const [Draweropen, setDrawerOpen] = useState(false);
  const [DrawerData, setDrawerData] = useState<API.InterfaceInfo>();
  const onGood = async (infoID : number) => {
    try{
      const res = await likeInterfaceInfoUsingPost({
        interfaceInfoId: infoID,
      });
      getLike();
      notification.info({
        message:"系统提示",
        description:'您不再喜欢该接口了',
        placement:'topRight',
        duration:2,
      });
    }catch(error){
      message.error('点赞失败');
    }

  };
  const onCollect = async (id) => {
    try {
      const res =  await collectInterfaceInfoUsingPost({
        interfaceInfoId: id,
      })
      getCollect();
      notification.info({
        message:"系统提示",
        description:res.data,
        placement:'topRight',
        duration:2,
      });
      if(res.data==='收藏成功') {
        setIsCollect[id](true);

      }
      else {
        setIsCollect[id](false)
      }

    }catch (e){
      message.error(e);
    }
  };
  const showDrawer = (values: API.InterfaceInfo) => {
    setDrawerOpen(true);
    setDrawerData(values);
  };



  const items: TabsProps['items'] = [
    {
      key: '1',
      label: (
        <span className="tab-label1" style={{ fontSize: 20, margin: 30, marginLeft: 30 }}>
          我的收藏
        </span>
      ),
      children: (
        <List
          key="1"
          dataSource={data}
          renderItem={(item, index) => {
            const apilink = `/interface_info/${item.id}`;
            return (

                  <List.Item
                      actions={[
                        <a
                            style={{
                              display: 'flex',
                              textAlign: 'right',
                              fontSize: '15px',
                            }}
                            key={item.id}
                            onClick={() => {
                              showDrawer(item);
                            }}
                        >
                          查看
                        </a>,
                        <a
                            style={{
                              display: 'flex',
                              textAlign: 'right',
                              fontSize: '15px',
                            }}
                            key={item.id}
                            href={apilink}
                        >
                          测试
                        </a>,
                        <a
                            style={{
                              display: 'flex',
                              textAlign: 'right',
                              fontSize: '15px',
                            }}
                            onClick={() => copyUrl(item.url)}
                            key="list-loadmore-more"
                        >
                          复制url
                        </a>,<a
                            style={{
                              display: 'flex',
                              textAlign: 'right',
                              fontSize: '15px',
                            }}
                            key={item.id}
                            onClick={()=>{onCollect(item.id)}}
                        >
                          移除
                        </a>,
                      ]}
                  >
                    <List.Item.Meta
                        avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                        title={
                          <a
                              style={{
                                fontSize: 16,
                              }}
                              href={apilink}
                          >
                            {item.name}
                          </a>
                        }
                        description={item.description}
                    />
                  </List.Item>
            );
          }}
        />
      ),
    },
    {
      key: '2',
      label: (
        <span className="tab-label2" style={{ fontSize: 20, margin: 30 }}>
          我的喜爱
        </span>
      ),
      children: (
          <List
              key="1"
              dataSource={like}
              renderItem={(item, index) => {
                const apilink = `/interface_info/${item.id}`;
                return (

                    <List.Item
                        actions={[
                          <a
                              style={{
                                display: 'flex',
                                textAlign: 'right',
                                fontSize: '15px',
                              }}
                              key={item.id}
                              onClick={() => {
                                showDrawer(item);
                              }}
                          >
                            查看
                          </a>,
                          <a
                              style={{
                                display: 'flex',
                                textAlign: 'right',
                                fontSize: '15px',
                              }}
                              key={item.id}
                              href={apilink}
                          >
                            测试
                          </a>,
                          <a
                              style={{
                                display: 'flex',
                                textAlign: 'right',
                                fontSize: '15px',
                              }}
                              onClick={() => copyUrl(item.url)}
                              key="list-loadmore-more"
                          >
                            复制url
                          </a>,<a
                              style={{
                                display: 'flex',
                                textAlign: 'right',
                                fontSize: '15px',
                              }}
                              key={item.id}
                              onClick={()=>{onGood(item.id)}}
                          >
                            移除
                          </a>,
                        ]}
                    >
                      <List.Item.Meta
                          avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                          title={
                            <a
                                style={{
                                  fontSize: 16,
                                }}
                                href={apilink}
                            >
                              {item.name}
                            </a>
                          }
                          description={item.description}
                      />
                    </List.Item>
                );
              }}
        />
      ),
    },
  ];

  const customRequest = async (image) => {
    const form = new FormData();
    form.append('image', image.file);
    // form 对象 就是我们上传接口需要的参数
    // 调用api接口进行请求 , uploadFile 是走我们封装的 请求的 , 请求头 token 都包含
    try {
      const res = await uploadUsingPost(form);
      const con = await updateUserUsingPost({
        id: currentUser.id,
        userAvatar: res.data,
      });
      setImageUrl(res.data);
      notification.info({
        message: '系统提示',
        description: '头像更新成功',
        placement: 'topRight',
        duration: 2,
      });
    } catch (e) {
      notification.info({
        message: '系统提示',
        description: '头像更新失败',
        placement: 'topRight',
        duration: 2,
      });
    }
    // 拿到调取接口返回的数据
  };
  const uploadProps = {
    name: 'image', //取值必须和接口参数中的文件参数名相同： MultipartFile file
    multiple: true,
    showUploadList: false,
    customRequest: customRequest,
  };
  const getLike = async () => {
    try {
      const res = await getLikesUsingGet({
        userId: currentUser.id,
      });

      if (res.data) {
        setLike(res?.data);

        console.log(like);
        return true;
      } else message.error('获取喜爱失败');
    } catch (e) {
      console.log(e);
    }
  };
  const getCollect = async () => {
    try {
      const res = await getCollectionsUsingGet({
        userId: currentUser.id,
      });
      if (res.data) setData(res?.data);
      else message.error('获取收藏失败');
    } catch (e) {
      console.log(e);
    }
  };
  const onChange = (key: string) => {};

  const getLoginUser = async () => {
      try {
          const res = await getLoginUserUsingGet();
          sessionStorage.setItem('loginUser', JSON.stringify(res.data));
          imminentUser = JSON.parse(sessionStorage.getItem('loginUser'));
          if (imminentUser.gender === 0) imminentUser.gender = '男';
          else imminentUser.gender = '女';
          setCurrentUser(imminentUser);
      }catch (e) {
          history.push('/user/login')
      }
  };
  const getBase64 = (img: FileType, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  const onClose = () => {
    loadData();
    setDrawerOpen(false);
  };
  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as FileType, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };
  const uploadButton = (
    <button style={{ border: 0, background: 'none', marginTop: 0 }} size={'small'} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 0 }}>Upload</div>
    </button>
  );
  const handleUpdate = async (fields: API.UserUpdateRequest) => {
    const hide = message.loading('个人信息更新中');
    fields.gender = fields.gender === '男' ? 0 : 1;
    try {
      const res = await updateUserUsingPost({
        id: currentUser.id,
        ...fields,
      });
      hide();
      message.success('个人信息更新成功');
      getLoginUser();
      return !!res;
    } catch (e) {
      console.log(e);
      return false;
    }
  };
  const  tryLegacyCopy=(url)=> {
    // 创建一个隐藏的textarea元素
    const textarea = document.createElement('textarea');
    textarea.value = url;
    textarea.style.position = 'fixed'; // 防止影响页面布局
    textarea.style.top = 0;
    textarea.style.left = 0;
    textarea.style.width = '1px';
    textarea.style.height = '1px';
    textarea.style.padding = 0;
    textarea.style.border = 'none';
    textarea.style.outline = 'none';
    textarea.style.boxShadow = 'none';
    textarea.style.background = 'transparent';

    document.body.appendChild(textarea);
    textarea.select();

    // 尝试复制
    const copied = document.execCommand('copy');

    // 清理
    document.body.removeChild(textarea);

    if (copied) {
      message.success('url已复制到剪切板');
    } else {
      console.error('Failed to copy URL to clipboard with the legacy method');
      // 可以进一步处理错误情况
    }
  }

  const copyUrl = (url: string) => {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
          .writeText(url)
          .then(() => {
            message.success('url已复制到剪切板');
          })
          .catch((error) => {
            console.error('Error copying URL to clipboard:', error);
            // 处理错误，例如显示警告信息
          });
    }else{
      tryLegacyCopy(url);
    }
  };
  const handleChangeKey = async () => {
    try {
      await changeAkandSkUsingPost({});
      getLoginUser();
      message.success('密钥更新成功');
    } catch (e) {
      console.log(e);
    }
  };
  useEffect(() => {
    getLoginUser();
    getCollect();
    getLike();
    if(imminentUser)
    setImageUrl(imminentUser.userAvatar === 'null' ? '' : imminentUser.userAvatar);

  }, []);

  useEffect(() => {
   if(imminentUser){
    if (imminentUser.gender === 0) imminentUser.gender = '男';
    else imminentUser.gender = '女';
    setCurrentUser(imminentUser);
     setImageUrl(currentUser.userAvatar === 'null' ? '' : currentUser.userAvatar);
}
  }, [currentUser]);
  return (
    <Card title={<p style={{fontSize:'22px',fontWeight:'bold'}}>用户中心</p>} bordered={false} style={{ width: '100%', fontFamily: 'PingFang SC',
        }}>
      {/* 用户头像 */}

      {/* 个人信息 */}
      <Space
        direction="vertical"
        size={60}
        style={{
          marginLeft: 20,
        }}
      >
        <Row gutter={24}>
          <Card
            hoverable="true"
            title={
              <p style={{   fontSize: 30, marginTop: 15, marginLeft: 20,marginBottom: 15 }}>
                您的个人卡片
              </p>
            }
            extra={
              <Button
                type={'primary'}
                style={{ fontSize: 15 }}
                onClick={() => {
                  handleUpdateModalOpen(true);
                }}
              >
                修改
              </Button>
            }
            style={{ width: '40%', height: '100%', animation: `${fadeIn} 0.6s cubic-bezier(0.4, 0, 0.2, 1) both`, }}
          >
            <Descriptions style={{ marginLeft: 16 }} column={1} size="middle">
              <Descriptions.Item style={{ display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',}}
              >
                <Upload
                  {...uploadProps}
                  name="avatar"
                  listType="picture"
                  className="avatar-uploader"
                  onChange={handleChange}
                  style={{
                    width: '400px',
                    height: '400px',
                    border: 'none',
                  }}
                >
                  {imageUrl ? (
                    <img
                      src={imageUrl}
                      alt="avatar"
                      style={{ width: 100, height: 110, marginLeft: 0 }}
                    />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </Descriptions.Item>
              <Descriptions.Item style={{              display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',marginBottom: 0,}}
              >
                <p style={{ fontSize: 21, fontWeight: 'bold',marginBottom: 0 }}>
                  {currentUser.userName === null? '野原新之助(默认昵称)' : currentUser.userName}
                </p>
              </Descriptions.Item>
              <Descriptions.Item style={{ display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',}}
              >
                <p style={{ fontSize: 17}}>
                  {currentUser.selfIntroduction === null
                    ? '您还没有介绍哦'
                    : currentUser.selfIntroduction}
                </p>
              </Descriptions.Item>
            </Descriptions>
              <Descriptions style={{ marginLeft: 16 }} column={1} size="middle">
                <Descriptions.Item
                    label="平台权限"
                    labelStyle={{ fontSize: 17, marginLeft: 20, marginBottom: 10 }}
                >
                  <p style={{ fontSize: 17, marginLeft: 10 }}>
                    {currentUser?.userRole === 'admin' ? '管理员阁下' : '普通用户'}
                  </p>
                </Descriptions.Item>
                <Descriptions.Item label="账户余额" labelStyle={{ fontSize: 17, marginLeft: 20 }}>
                  <p style={{ fontSize: 17, marginLeft: 10 }}>{currentUser?.remainingPoints}</p>
                </Descriptions.Item>
              <Descriptions.Item label="AccessKey" labelStyle={{ fontSize: 17, marginLeft: 20 }}>
                <p style={{ fontSize: 17, marginLeft: 5 }}>{currentUser.accessKey}</p>
              </Descriptions.Item>

              <Descriptions.Item
                label="SecretKey"
                labelStyle={{ fontSize: 17, marginLeft: 20, marginBottom: 20 }}
              >
                {showSecretKey ? (
                  <>
                    <p ellipsis={{ tooltip: true }} style={{ fontSize: 17, marginLeft: 5 }}>
                      {currentUser.secretKey}
                    </p>
                    <Popconfirm
                      title="确认关闭密钥？"
                      onConfirm={() => setShowSecretKey(false)}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button
                        ghost="true"
                        shape="round"
                        icon={<EyeOutlined />}
                        danger
                        style={{
                          marginLeft: 20,
                          borderWidth: 0,
                        }}
                      >
                        关闭秘钥
                      </Button>
                    </Popconfirm>
                  </>
                ) : (
                  <Popconfirm
                    title="确认显示密钥？"
                    onConfirm={() => setShowSecretKey(true)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button
                      style={{
                        borderWidth: 0,
                      }}
                      ghost="true"
                      shape="round"
                      icon={<EyeOutlined />}
                      danger
                    >
                      显示秘钥
                    </Button>
                  </Popconfirm>
                )}
              </Descriptions.Item>


              {/*handleChangeKey()*/}
              <Descriptions.Item label="更换密钥" labelStyle={{ fontSize: 17, marginLeft: 20 }}>
                <Popconfirm
                  title="确认更换密钥？这可能对您的接口鉴权造成不可逆的影响"
                  onConfirm={() => handleChangeKey()}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button shape="round" type={'primary'} danger>
                    更换
                  </Button>
                </Popconfirm>
              </Descriptions.Item>
            </Descriptions>
          </Card>

          <Col span={14}>
            <Card style={{ height: '100%',width: '100%',maxHeight: '100%', overflowY: 'auto', animation: `${fadeIn} 0.6s cubic-bezier(0.4, 0, 0.2, 1) both`,}}>
            <Tabs
                defaultActiveKey="1"
                items={items}
                onChange={onChange}
                style={{ fontSize: 16, marginleft: 30 }}
            ></Tabs>




            </Card>

          </Col>
        </Row>
        <Drawer
            width={720}
            styles={{fontSize:'18px'}}
            placement="right"
            closable={false}
            onClose={onClose}
            open={Draweropen}
            extra={<Space></Space>}
            size="default"
            keyboard={true}
        >
          <Card
              title={<p style={{fontSize: '24px',fontWeight: 'bold',marginTop: 20}}>接口详细信息</p>}
              style={{
                width: 580,
                fontSize: 55,
                marginBottom: 24,
                marginLeft: 5,
                borderRadius: 10,
                border: 0,
                justifyContent: 'space-between',
              }}
          >
            <Row>
              <Col span={12}>
                <DescriptionItem title="ID" content={DrawerData?.id}/>
              </Col>
              <Col span={12}>
                <DescriptionItem title="Name" content={DrawerData?.name} />
              </Col>
            </Row>
            <Row >
              <Col span={24}>
                <DescriptionItem title="描述" content={DrawerData?.description} style={{ whiteSpace: 'pre-wrap' }} />
              </Col>
            </Row>
            <Row>
              <Col>
                <DescriptionItem title="接口URL" content={DrawerData?.url} />
              </Col>
            </Row>
            <Row>
              <Col>
                <DescriptionItem title="请求头" content={DrawerData?.requestHeader} />
              </Col>
            </Row>
            <Row>
              <Col>
                <DescriptionItem title="响应头" content={DrawerData?.responseHeader} />
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <DescriptionItem
                    title="接口状态"
                    content={DrawerData?.status == 1 ? '已发布' : '已下线'}
                />
              </Col>
              <Col>
                <DescriptionItem title="请求方式" content={DrawerData?.method} />
              </Col>
            </Row>
            <Row>
              <Col>
                <DescriptionItem title="创建时间" content={DrawerData?.createTime} />
              </Col>
            </Row>
            <Row>
              <Col>
                <DescriptionItem title="更新时间" content={DrawerData?.updateTime} />
              </Col>
            </Row>
            <Row>
              <Col>
                <DescriptionItem title="请求参数" content={DrawerData?.requestParams} />
              </Col>
            </Row>
          </Card>
          <Space
              style={{
                display: 'flex',
                justifyContent: 'flex-end',
                alignItems: 'flex-end',
              }}
          >
            <Button onClick={onClose}>Cancel</Button>
            <Button type="primary" onClick={onClose}>
              OK
            </Button>
          </Space>
        </Drawer>
        {/*调节tab内文字大小*/}

      </Space>
      <UserUpdateModal
        values={currentUser}
        isOpen={updateModalOpen}
        columns={simpleColumns}
        onCancel={() => {
          handleUpdateModalOpen(false);
        }}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      />
    </Card>

    // 用户信息更新模块
  );

};

export default UserCenter;
